﻿using Chen.CefWebKit.Factory.UrlFilter;
using Chen.CefWebKit.WebBrowser;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Chen.CefWebKit.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //初始化操作
            BrowserForm bf = new BrowserForm();//初始化主窗体
            var Task = new BrowserTabUserControl();//创建标签页任务
            bf.AddTask("test_task", Task);//将任务添加进主窗体
            //监控Response抓取数据
            Task.urlFilterFacotrys.AddResponseUrlFilterFacotry("https://m.facebook.com/stories.php", (request, response, content) =>
            {
                string html = Encoding.UTF8.GetString(content);
                Task.TextMessageBox.WriteLine($"{html}");
            });
            //监控Response抓取资源文件
            Task.urlFilterFacotrys.AddResponseUrlFilterFacotry(new UrlFileFilter("", UrlFileType.ANY, (request, response, content) =>
            {
                //储存文件
                string filename = request.Url.Split('?')[0].Split('/').Last();
                FileStream fs = new FileStream("pic/" + filename, FileMode.Create);
                fs.Write(content, 0, content.Length);
                fs.Close();
            }));

            //基本用法
            string url = "https://m.facebook.com/";
            Task.TextMessageBox.WriteLine($"开始加载页面{url}");
            if (Task.LoadAndWaitRender(url, "img"))//加载一个页面,通过判断页面是否包含某个标签等待加载完成，若超时未加载成功则视为失败
            {
                Task.TextMessageBox.WriteLine($"页面{url}加载成功！");
            }
            else
            {
                Task.TextMessageBox.WriteLine($"页面{url}加载失败！");
            }

            //Task.TextMessageBox.WriteLine($"10秒后跳转至模拟登录演示页面");
            //Thread.Sleep(10000);

            ////进阶用法
            //Task.LoadAndWaitRender("https://passport.cnblogs.com/user/signin", "#input1");
            //string username = "test";
            //string password = "test";
            //Task.TextMessageBox.WriteLine($"尝试使用用户名：{username} 密码：{password} 登录");
            //Task.RunScript(JavaScriptLibrary.BindValue("#input1", username));//将用户名与密码绑定至页面输入框内
            //Task.RunScript(JavaScriptLibrary.BindValue("#input2", password));

            //Thread.Sleep(1000);
            //Task.RunScript(JavaScriptLibrary.ButtonClick("#signin"));//模拟按下按钮提交表单，也可用JS直接模拟提交表单

            //var cookies = Task.GetAllCookie();//获得所有Cookie

            Console.ReadLine();
        }
    }
}
